<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use DB;
class CategoryController extends Controller
{
    /**
     * @return Category
     */
    public function cate()
    {
        return $cate = new Category();
    }

    /**
     * 获取分类表(查)
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getTable(Request $request)
    {
        $total = Category::all();
        $data = Category::select(DB::raw('*,concat(path,",",id) as paths'))->where('title', 'like', '%' . $request->input('keywords') . '%')->orderBy('paths')->paginate(3);
//        foreach ($data as $key => $value) {
//            $count = substr_count($value->path,',');
//            $value->title = str_repeat('--|',$count).$value->title;
//        }
        return view('admin/category_table',['data' => $data,'total' => $total,'request' => $request->all()]);
    }

    /**
     * 添加分类(增)
     * @param Request $request
     * @param int $parent_id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postAdd(Request $request,$parent_id=0)
    {
        $result = $this->cate()->add($request,$parent_id);
        if ($result['status'] == 0 )
            return back()->with('error', $result['error']);
        elseif ($result['status'] == 1 )
            return back()->with('msg', $result['msg']);
        elseif($result['status'] == -1 )
            return back()->withErrors($result['error']);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function postEdit(Request $request)
    {
        $result = $this->cate()->edit($request);
        if ($result['status'] == 0 )
            return back()->with('error', $result['error']);
        elseif ($result['status'] == 1 )
            return back()->with('msg', $result['msg']);
        elseif($result['status'] == -1 )
            return back()->withErrors($result['error']);
    }

    /**
     *软删除(回收站操作)(删)
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getDelete($id)
    {
        $result = $this->cate()->cateDelete($id);
        if($result['status'])
            return back()->with('msg',$result['msg']);
        else
            return back()->with('error',$result['msg']);
    }
}

